"use client";

import React, { useState, useEffect } from 'react';
import axios from 'axios';
import dayjs from 'dayjs';
import dynamic from 'next/dynamic';
import { useNotifications } from '@/context/NotificationContext';

// Dynamically import ApexCharts to avoid SSR issues
const Chart = dynamic(() => import('react-apexcharts'), { ssr: false });

interface Transaction {
  id: string;
  hash: string;
  chain: string;
  from: string;
  to: string;
  value: string;
  valueUSD: number;
  timestamp: string;
  tokenSymbol?: string;
}

interface Statistics {
  overview: {
    totalTransactions: number;
    uniqueAddresses: number;
    totalVolume: number;
    activeChains: number;
    recentAlerts: number;
  };
  trends: {
    daily: Array<{
      date: string;
      transactions: number;
      volume: number;
    }>;
  };
  distribution: {
    byChain: Array<{
      chain: string;
      transactions: number;
      volume: number;
    }>;
  };
  lastUpdated: string;
}

const ChainWatchDashboard: React.FC = () => {
  const [stats, setStats] = useState<Statistics | null>(null);

  // Get explorer URL
  const getExplorerUrl = (chain: string, hash: string): string => {
    const explorers = {
      ethereum: `https://etherscan.io/tx/${hash}`,
      bsc: `https://bscscan.com/tx/${hash}`,
      polygon: `https://polygonscan.com/tx/${hash}`,
      bitcoin: `https://blockchair.com/bitcoin/transaction/${hash}`,
      base: `https://basescan.org/tx/${hash}`,
      solana: `https://solscan.io/tx/${hash}`
    };
    return explorers[chain as keyof typeof explorers] || '#';
  };
  const [recentTransactions, setRecentTransactions] = useState<Transaction[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [sseConnected, setSseConnected] = useState(false);
  const { wsConnected, notifications } = useNotifications();

  // Fetch statistics data
  const fetchStatistics = async () => {
    console.log('🔄 Fetching statistics...');
    try {
      const response = await axios.get('/api/statistics', {
        timeout: 30000, // 30秒超时
      });
      console.log('📊 Statistics response:', response.status, response.data);
      
      if (response.data.success) {
        setStats(response.data.data);
        setError(null); // 清除之前的错误
        console.log('✅ Statistics loaded successfully');
      } else {
        console.error('❌ Statistics API returned error:', response.data.error);
        setError(`Statistics API Error: ${response.data.error}`);
      }
    } catch (err) {
      console.error('💥 Failed to fetch statistics:', err);
      if (axios.isAxiosError(err) && err.response) {
        console.error('Response data:', err.response.data);
        setError(`Failed to load statistics: ${err.response.data?.error || err.message}`);
      } else if (axios.isAxiosError(err) && err.code === 'ECONNABORTED') {
        setError('Request timeout - API is taking too long to respond');
      } else {
        setError('Failed to load statistics data - please check network connection');
      }
    }
  };

  // Fetch recent transactions
  const fetchRecentTransactions = async () => {
    console.log('🔄 Fetching transactions...');
    try {
      const response = await axios.get('/api/transactions?limit=10', {
        timeout: 30000, // 30秒超时
      });
      console.log('💳 Transactions response:', response.status, response.data);
      
      if (response.data.success) {
        // 处理可能的数据格式差异
        const data = response.data.data;
        setRecentTransactions(data.items || data || []);
        console.log('✅ Transactions loaded successfully:', data.items?.length || 0, 'items');
      } else {
        console.error('❌ Transactions API returned error:', response.data.error);
        setRecentTransactions([]); // 设置为空数组而不是保持 loading 状态
      }
    } catch (err) {
      console.error('💥 Failed to fetch transaction data:', err);
      setRecentTransactions([]); // 设置为空数组，让页面可以正常显示
    }
  };

  useEffect(() => {
    const loadInitialData = async () => {
      setLoading(true);
      console.log('🚀 Loading initial dashboard data...');
      
      // 设置超时机制 - 30秒后强制停止加载
      const timeoutId = setTimeout(() => {
        console.warn('⏰ Loading timeout - forcing stop');
        setLoading(false);
        setError('Loading timeout - please refresh the page');
      }, 30000);

      try {
      await Promise.all([fetchStatistics(), fetchRecentTransactions()]);
        console.log('✅ Initial data loaded successfully');
      } catch (error) {
        console.error('💥 Error loading initial data:', error);
      } finally {
        clearTimeout(timeoutId);
      setLoading(false);
        console.log('🏁 Initial loading completed');
      }
    };

    // 只加载一次初始数据
    loadInitialData();

    // SSE连接管理
    let eventSource: EventSource | null = null;
    let reconnectTimer: NodeJS.Timeout | null = null;
    let reconnectAttempts = 0;
    const maxReconnectAttempts = 5;
    const baseReconnectDelay = 1000; // 1秒
    let isComponentMounted = true; // 组件挂载状态

    const connectSSE = () => {
      // 如果组件已卸载，不要重连
      if (!isComponentMounted) return;
      
      if (eventSource) {
        eventSource.close();
        eventSource = null;
      }
      
      try {
        console.log('🔗 Connecting to SSE...');
        eventSource = new EventSource('/api/sse');
        
        eventSource.onopen = () => {
          console.log('✅ SSE connection established');
          setSseConnected(true);
          reconnectAttempts = 0; // 重置重连计数
        };

        eventSource.onmessage = (event) => {
          if (!isComponentMounted) return; // 组件已卸载，忽略消息
          
          try {
            const data = JSON.parse(event.data);
            console.log('📨 SSE message:', data.type);
            
            if (data.type === 'transaction') {
              // 新交易数据
              setRecentTransactions(prev => [data, ...prev.slice(0, 9)]); // 只保留最新10条

            } else if (data.type === 'statistics') {
              // 统计数据更新
              if (data.data) {
                setStats(data.data);
                console.log('📊 Updated statistics from SSE');
              }
            } else if (data.type === 'alert') {
              console.log('🚨 Received alert:', data.message);
            } else if (data.type === 'connected' || data.type === 'heartbeat') {
              // 连接确认和心跳消息，不需要特殊处理
            }
          } catch (error) {
            console.error('❌ Error parsing SSE data:', error);
          }
        };

        eventSource.onerror = (error) => {
          console.error('💥 SSE connection error:', error, eventSource?.readyState);
          setSseConnected(false);
          
          if (!isComponentMounted) return; // 组件已卸载，不要重连
          
          if (eventSource?.readyState === EventSource.CLOSED) {
            console.log('🔄 SSE connection closed, attempting to reconnect...');
            
            if (reconnectAttempts < maxReconnectAttempts) {
              const delay = baseReconnectDelay * Math.pow(2, reconnectAttempts); // 指数退避
              console.log(`⏰ Reconnecting in ${delay}ms (attempt ${reconnectAttempts + 1}/${maxReconnectAttempts})`);
              
              reconnectTimer = setTimeout(() => {
                if (isComponentMounted) { // 再次检查组件状态
                reconnectAttempts++;
                connectSSE();
                }
              }, delay);
            } else {
              console.error('❌ Max reconnection attempts reached, giving up');
              setError('Real-time connection failed. Please refresh the page.');
            }
          }
        };
      } catch (error) {
        console.error('❌ Failed to create SSE connection:', error);
        setSseConnected(false);
      }
    };

    // 初始连接
    connectSSE();
    
    return () => {
      console.log('🔌 Cleaning up SSE connection');
      isComponentMounted = false; // 标记组件已卸载
      
      if (reconnectTimer) {
        clearTimeout(reconnectTimer);
        reconnectTimer = null;
      }
      
      if (eventSource) {
        eventSource.close();
        eventSource = null;
      }
    };
  }, []); // 空依赖数组，确保只在组件挂载时执行一次

  // Monitor notifications for new transactions to update the transaction list
  useEffect(() => {
    const latestNotification = notifications[0];
    if (latestNotification && 
        latestNotification.type === 'info' && 
        latestNotification.title === 'Large Transaction Detected' &&
        latestNotification.data) {
      
      const transaction = latestNotification.data;
      
      // Ensure transaction has a unique ID
      const newTransaction = {
        ...transaction,
        id: transaction.id || transaction.hash || `${transaction.chain}-${Date.now()}-${Math.random()}`
      };
      
      setRecentTransactions(prev => {
        // Remove any existing transaction with the same hash to avoid duplicates
        const filtered = prev.filter(tx => tx.hash !== newTransaction.hash);
        return [newTransaction, ...filtered.slice(0, 9)];
      });
    }
  }, [notifications]);

  // Generate chart data for 24 hours
  const generateChartData = () => {
    const data = [];
    for (let i = 23; i >= 0; i--) {
      const hour = dayjs().subtract(i, 'hour');
      data.push({
        x: hour.valueOf(),
        y: Math.floor(Math.random() * 1000000) + 100000
      });
    }
    return data;
  };

  const chartOptions = {
    chart: {
      type: 'line' as const,
      height: 350,
      background: 'transparent',
      toolbar: {
        show: false
      }
    },
    theme: {
      mode: 'light' as const
    },
    dataLabels: {
      enabled: false
    },
    stroke: {
      curve: 'smooth' as const,
      width: 2
    },
    xaxis: {
      type: 'datetime' as const,
      labels: {
        format: 'HH:mm'
      }
    },
    yaxis: {
      labels: {
        formatter: (value: number) => `$${value.toLocaleString()}`
      }
    },
    tooltip: {
      x: {
        format: 'HH:mm'
      },
      y: {
        formatter: (value: number) => `$${value.toLocaleString()}`
      }
    },
    grid: {
      strokeDashArray: 3
    },
    colors: ['#3B82F6']
  };

  const chartSeries = [{
    name: 'Transaction Volume',
    data: generateChartData()
  }];

  const getChainColor = (chain: string) => {
    const colors: Record<string, string> = {
      ethereum: 'bg-blue-500',
      bsc: 'bg-yellow-500',
      bitcoin: 'bg-orange-500',
      base: 'bg-cyan-500',
      solana: 'bg-purple-500',
      polygon: 'bg-purple-600'
    };
    return colors[chain] || 'bg-green-500';
  };

  // 如果加载超过5秒，显示页面但标记为加载中
  if (loading) {
    return (
      <div className="p-6 space-y-6">
        <div className="mb-8">
          <div className="flex items-center justify-between">
            <div>
              <h1 className="text-3xl font-bold text-gray-900 dark:text-white mb-2">ChainWatch Dashboard</h1>
              <p className="text-gray-600 dark:text-gray-400 text-lg">
                Loading data...
              </p>
            </div>
            <div className="flex items-center gap-3 px-4 py-2 rounded-lg text-sm font-medium bg-yellow-500/10 text-yellow-400 border border-yellow-500/20">
              <div className="w-2 h-2 rounded-full bg-yellow-400 animate-pulse"></div>
              Loading...
            </div>
          </div>
        </div>

        {error && (
          <div className="p-4 mb-4 text-red-700 bg-red-100 border border-red-300 rounded dark:bg-red-900 dark:text-red-200 dark:border-red-600">
            <p className="font-medium">Loading Error</p>
            <p className="text-sm">{error}</p>
          </div>
        )}

        {/* 显示加载中的占位符 */}
        <div className="grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-4">
          {[1,2,3,4].map(i => (
            <div key={i} className="bg-white dark:bg-zinc-800 shadow-sm rounded-lg p-4 animate-pulse">
              <div className="h-4 bg-gray-200 dark:bg-gray-700 rounded w-3/4 mb-3"></div>
              <div className="h-8 bg-gray-200 dark:bg-gray-700 rounded w-1/2"></div>
            </div>
          ))}
        </div>
      </div>
    );
  }

  return (
    <div className="p-6 space-y-6">
      {/* Header */}
      <div className="mb-8">
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-3xl font-bold text-gray-900 dark:text-white mb-2">ChainWatch Dashboard</h1>
            <p className="text-gray-600 dark:text-gray-400 text-lg">
              Real-time monitoring of large blockchain transactions (Threshold: $50,000+)
            </p>
          </div>
          <div className={`flex items-center gap-3 px-4 py-2 rounded-lg text-sm font-medium ${
            sseConnected 
              ? 'bg-green-500/10 text-green-400 border border-green-500/20' 
              : 'bg-red-500/10 text-red-400 border border-red-500/20'
          }`}>
            <span className={`w-2 h-2 rounded-full ${sseConnected ? 'bg-green-400 animate-pulse' : 'bg-red-400'}`}></span>
            {sseConnected ? 'Live Connected (SSE)' : 'Disconnected'}
          </div>
        </div>
      </div>

      {error && (
        <div className="p-4 mb-4 text-red-700 bg-red-100 border border-red-300 rounded dark:bg-red-900 dark:text-red-200 dark:border-red-600">
          <p className="font-medium">Data Loading Error</p>
          <p className="text-sm">{error}</p>
        </div>
      )}

      {/* Statistics Cards */}
      <div className="grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-4">
        <div className="bg-white dark:bg-zinc-800 shadow-sm rounded-lg p-4 hover:shadow-md transition-all duration-300">
          <div className="flex items-center justify-between">
            <div>
              <h3 className="text-sm font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wide">Today's Transactions</h3>
              <p className="text-3xl font-bold text-gray-800 dark:text-white/90 mt-3">
                {stats?.overview.totalTransactions || 0}
              </p>
              <div className="flex items-center mt-2">
                <span className="text-xs text-gray-500 dark:text-gray-400">Large transfers</span>
              </div>
            </div>
            <div className="w-12 h-12 bg-blue-500/10 rounded-xl flex items-center justify-center">
              <svg className="w-6 h-6 text-blue-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
              </svg>
            </div>
          </div>
        </div>
        
        <div className="bg-white dark:bg-zinc-800 shadow-sm rounded-lg p-4 hover:shadow-md transition-all duration-300">
          <div className="flex items-center justify-between">
            <div>
              <h3 className="text-sm font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wide">Today's Volume</h3>
              <p className="text-3xl font-bold text-green-400 mt-3">
                ${(stats?.overview.totalVolume || 0).toLocaleString()}
              </p>
              <div className="flex items-center mt-2">
                <span className="text-xs text-green-400">USD Value</span>
              </div>
            </div>
            <div className="w-12 h-12 bg-green-500/10 rounded-xl flex items-center justify-center">
              <svg className="w-6 h-6 text-green-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1" />
              </svg>
            </div>
          </div>
        </div>
        
        <div className="bg-white dark:bg-zinc-800 shadow-sm rounded-lg p-4 hover:shadow-md transition-all duration-300">
          <div className="flex items-center justify-between">
            <div>
              <h3 className="text-sm font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wide">Total Detected</h3>
              <p className="text-3xl font-bold text-blue-400 mt-3">
                {stats?.overview.uniqueAddresses || 0}
              </p>
              <div className="flex items-center mt-2">
                <span className="text-xs text-blue-400">All time</span>
              </div>
            </div>
            <div className="w-12 h-12 bg-blue-500/10 rounded-xl flex items-center justify-center">
              <svg className="w-6 h-6 text-blue-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 7h8m0 0v8m0-8l-8 8-4-4-6 6" />
              </svg>
            </div>
          </div>
        </div>
        
        <div className="bg-white dark:bg-zinc-800 shadow-sm rounded-lg p-4 hover:shadow-md transition-all duration-300">
          <div className="flex items-center justify-between">
            <div>
              <h3 className="text-sm font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wide">Average Amount</h3>
              <p className="text-3xl font-bold text-purple-400 mt-3">
                ${(stats?.overview.recentAlerts || 0).toLocaleString()}
              </p>
              <div className="flex items-center mt-2">
                <span className="text-xs text-purple-400">Per transaction</span>
              </div>
            </div>
            <div className="w-12 h-12 bg-purple-500/10 rounded-xl flex items-center justify-center">
              <svg className="w-6 h-6 text-purple-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 7h6m0 10v-3m-3 3h.01M9 17h.01M9 14h.01M12 14h.01M15 11h.01M12 11h.01M9 11h.01M7 21h10a2 2 0 002-2V5a2 2 0 00-2 2v14a2 2 0 002 2z" />
              </svg>
            </div>
          </div>
        </div>
      </div>

      {/* Chart and Recent Transactions */}
              <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
          <div className="lg:col-span-2">
            <div className="bg-white dark:bg-zinc-800 shadow-sm rounded-lg p-4">
              <div className="flex items-center justify-between mb-6">
                <h3 className="text-xl font-bold text-gray-800 dark:text-white/90">
                  24-Hour Transaction Trend
                </h3>
                <div className="flex items-center gap-2">
                  <span className="w-2 h-2 bg-blue-400 rounded-full"></span>
                  <span className="text-sm text-gray-500 dark:text-gray-400">Live Data</span>
                </div>
              </div>
            {typeof window !== 'undefined' && (
              <Chart
                options={chartOptions}
                series={chartSeries}
                type="line"
                height={300}
              />
            )}
          </div>
        </div>

                  <div className="lg:col-span-1">
            <div className="bg-white dark:bg-zinc-800 shadow-sm rounded-lg p-4">
              <div className="flex items-center justify-between mb-4">
                <h3 className="text-xl font-bold text-gray-800 dark:text-white/90">Recent Transactions</h3>
                <div className="text-xs text-gray-500 dark:text-gray-400 rounded-xl bg-slate-100 dark:bg-zinc-700 hover:bg-slate-200 dark:hover:bg-zinc-600 px-2 py-1">
                  Live
                </div>
              </div>
            <div className="space-y-3 max-h-80 overflow-y-auto">
              {recentTransactions && recentTransactions.length > 0 ? (
                recentTransactions.map((tx, index) => (
                  <div key={`${tx.hash}-${index}`} className="group p-4 border border-gray-200 dark:border-gray-700/50 dark:bg-gray-800/30 rounded-xl hover:dark:bg-gray-700/50 hover:border-blue-500/30 transition-all duration-300 cursor-pointer">
                    <div className="flex items-center justify-between mb-3">
                      <span className={`px-3 py-1.5 text-xs font-bold text-white rounded-lg ${getChainColor(tx.chain)} shadow-sm`}>
                        {tx.chain.toUpperCase()}
                      </span>
                      <div className="text-right">
                        <div className="text-xs text-gray-500 dark:text-gray-400">
                          {dayjs(tx.timestamp).format('HH:mm:ss')}
                        </div>
                        <div className="text-xs text-gray-400">
                          {dayjs(tx.timestamp).format('MM-DD')}
                        </div>
                      </div>
                    </div>
                    
                    <div className="mb-3">
                      <a 
                        href={getExplorerUrl(tx.chain, tx.hash)} 
                        target="_blank" 
                        rel="noopener noreferrer"
                        className="text-xs font-mono text-blue-600 hover:text-blue-800 dark:text-blue-400 dark:hover:text-blue-300 transition-colors hover:underline"
                      >
                        {tx.hash.substring(0, 12)}...{tx.hash.substring(tx.hash.length - 10)}
                      </a>
                    </div>
                    
                    <div className="flex justify-between items-end">
                      <div>
                        <div className="text-xl font-bold text-green-400">
                          ${tx.valueUSD.toLocaleString()}
                        </div>
                        {tx.tokenSymbol && (
                          <div className="text-xs text-gray-400 mt-1">
                            {parseFloat(tx.value).toFixed(2)} {tx.tokenSymbol}
                          </div>
                        )}
                      </div>
                      <div className="text-right">
                        <div className="w-2 h-2 bg-green-400 rounded-full animate-pulse"></div>
                      </div>
                    </div>
                  </div>
                ))
              ) : (
                <div className="text-center py-8">
                  <p className="text-gray-500 dark:text-gray-400">Waiting for transaction data...</p>
                  <p className="text-sm text-gray-400 dark:text-gray-500 mt-2">
                    Monitors are scanning blocks, please wait
                  </p>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>

      {/* Blockchain Statistics */}
      <div className="bg-white dark:bg-zinc-800 shadow-sm rounded-lg p-4">
        <div className="flex items-center justify-between mb-6">
          <h3 className="text-xl font-bold text-gray-800 dark:text-white/90">Blockchain Statistics</h3>
          <div className="text-sm text-gray-500 dark:text-gray-400">
            Active Networks
          </div>
        </div>
                                {stats?.distribution?.byChain && Array.isArray(stats.distribution.byChain) && stats.distribution.byChain.length > 0 ? (
            <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4">
              {stats.distribution.byChain.map((chainStat) => (
              <div key={chainStat.chain} className="group text-center p-5 border border-gray-200 dark:border-gray-700/50 dark:bg-gray-800/30 rounded-xl hover:dark:bg-gray-700/50 hover:border-blue-500/30 transition-all duration-300 cursor-pointer">
                <div className={`inline-flex items-center justify-center w-10 h-10 rounded-xl mb-4 ${getChainColor(chainStat.chain)}/10`}>
                  <span className={`text-xs font-bold ${getChainColor(chainStat.chain).replace('bg-', 'text-')}`}>
                    {chainStat.chain.substring(0, 3).toUpperCase()}
                  </span>
                </div>
                <div className="text-2xl font-bold text-gray-900 dark:text-white mb-1">
                  {chainStat.transactions}
                </div>
                <div className="text-xs text-gray-500 dark:text-gray-400 mb-2">transactions</div>
                <div className="text-sm font-bold text-green-400">
                  ${(chainStat.volume || 0).toLocaleString()}
                </div>
                <div className="text-xs text-gray-400 mt-1">
                  volume
                </div>
              </div>
            ))}
          </div>
        ) : (
          <div className="text-center py-8">
            <p className="text-gray-500 dark:text-gray-400">No blockchain statistics data available</p>
          </div>
        )}
      </div>
    </div>
  );
};

export default ChainWatchDashboard; 